package com.chenshuang.web;

import com.chenshuang.bean.CartGoods;
import com.chenshuang.bean.Goods;
import com.chenshuang.service.CartService;
import com.chenshuang.service.GoodsService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "CartServlet", value = "/cart")
public class CartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        CartGoods cartGoods = new CartGoods();
        GoodsService goodsService = new GoodsService();
        CartGoods cartgoods = goodsService.queryGoods(id,cartGoods);
        // 查询虚拟商品对象
        Goods goods = goodsService.queryGoods(id);
        //把获取 到的商品对象集合 加到session中
        HttpSession session = request.getSession();
        // 强行获得 添加到购物车的商品集合
        List<CartGoods> cartlist;
        cartlist = (List<CartGoods>) session.getAttribute("cartlist");

        if (cartlist==null){
            cartlist = new ArrayList<>();
        }

        boolean flog = true;
        for (CartGoods cg : cartlist) {
            System.out.println("================= 外");
            if(goods.equals(cg.getGoods())){
                System.out.println("================ 内");
                flog = false;
                break;
            }
        }
        if (flog){
            cartlist.add(cartgoods);
        }else {
            request.getRequestDispatcher("addgoods").forward(request,response);
        }

//        cartlist.add(cartgoods);

        // 把cartgoods上传到共享域供 deleteservlet页面获取、
        session.setAttribute("cartgoods",cartgoods);

        //上传共享域
        session.setAttribute("cartlist",cartlist);
//        session.setAttribute("goods",virgoods);
        // 转发 到 购物车页面
        request.getRequestDispatcher("cart.jsp").forward(request,response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//        cartgoods.getVirGoods().setNum(1);

        //        boolean flog = true;
//        for (CartGoods cg : cartlist) {
//            System.out.println("================= 外");
//            if(goods.equals(cg.getGoods())){
//                System.out.println("================ 内");
//                flog = false;
//                break;
//            }
//        }
//        if (flog){
//            cartlist.add(cartgoods);
//        }else {
//            request.getRequestDispatcher("addgoods").forward(request,response);
//        }
    }
}
